//引入模块
const express = require("express");
//引入mysql连接池对象
const query = require("../util/query.js");
const Token = require('../util/token.js');
const response = require("./response");

//创建空路由器
let router = express.Router();
//挂载路由
// 1.6. 订单管理
//===============================================
// 1.6.1 创建订单 order/create
// 参数名	参数说明	备注
// address	收货地址对象{}
// amount 总金额
// note	备注信息
// goodsList	购买商品数组,如：
//	[{"id":"109","count":5,"price":129},
//   {"id":"111","count":23,"price":222}]  这里的id是指商品id
router.post("/create", async (req, res) => {
    //是否已登录
    const token = req.headers.authorization // 取到请求头中Token
    let result = Token.verify(token);
    if (result.code != 1) {
        res.send({
            code: 401,
            msg: "Token错误，请登录验证!",
            data: {}
        });
        return;
    }
    let user = result.data;

    //以下代码没有考虑数据库的事务操作，需要进一步完善的....
    try {
        //1获取收货人地址编号数据
        let address = req.body.address;
        if (!address) throw "收货人地址不能为空";
        let note = req.body.note;
        let amount = req.body.amount || 0;
        if (!req.body.goodsList) throw "购买商品不能为空";


        let goodsList = [];

        req.body.goodsList.forEach(item => goodsList.push(item));  //传递过来的订单商品列表

        console.log(goodsList);

        // 判断库存是否全部充足，并计算总价格
        let orderGoods = []; //待新建的订单商品列表
        for (let i = 0; i < goodsList.length; i++) {
            //判断每个商品库存数量是否满足
            let item = goodsList[i];
            let sql = `select * from goods where id = ${item.id} AND num >= ${item.count} AND status = 1`;
            let result = await query(sql);

            if (result.length == 0) throw `部分商品库存不足`;

            //继续处理该商品
            orderGoods.push({
                goods_id: item.id,
                count: item.count,
                price: item.price,
            });

            //修改商品的库存数量
            sql = `update goods set num = num - ${item.count} where id=${item.id}`;
            await query(sql);
        }

        // 创建订单
        let order = {};
        order.user_id = user.id;
        order.address_name = address.name;
        order.address_tel = address.tel;
        order.address_detail = `${address.city}-${address.county}-${address.detail}`;
        order.note = note;
        order.amount = amount;
        sql = "INSERT INTO user_order SET ?";
        result = await query(sql, [order]);
        let order_id = result.insertId;  //获取新订单的编号
        //插入订单项数据
        for (let i = 0; i < orderGoods.length; i++) {
            let goods = orderGoods[i];
            goods.order_id = order_id; //订单商品记录添加订单编号值
            sql = "INSERT INTO user_order_goods SET ?";
            await query(sql, [goods]);
        }

        res.send({code: 1, msg: `创建订单成功`, data: order_id});

    } catch (error) {
        res.send({code: -1, msg: `创建订单失败, 错误信息: ${error}`}); //throw err;
    }
});
//===============================================
// 1.6.1 创建订单 order/create
// 参数名	参数说明	备注
// address_id	收货地址id
// note	备注信息
// goods	购买商品信息数组,如：
//	[{"id":"109","count":5,"selected":true},
//   {"id":"111","count":23,"selected":true}]
router.post("/create_old", async (req, res) => {
    //是否已登录
    const token = req.headers.authorization // 取到请求头中Token
    let result = Token.verify(token);
    if (result.code != 1) {
        res.send({
            code: 401,
            msg: "Token错误，请登录验证!",
            data: {}
        });
        return;
    }
    let user = result.data;

    //以下代码没有考虑数据库的事务操作，需要进一步完善的....
    try {
        //1获取收货人地址编号数据
        let address_id = parseInt(req.body.address_id);
        if (!address_id) throw "收货人地址不能为空";
        let note = req.body.note;

        if (!req.body.goods) throw "购买商品不能为空";

        let goodsList = JSON.parse(req.body.goods);  //传递过来的订单商品列表

        //处理获取收货地址
        let sql = `select * from user_address where user_id = ${user.id} AND id = ${address_id}`;
        let result = await query(sql);
        if (result.length == 0) throw "收货地址不存在";
        let address = result[0];

        // 判断库存是否全部充足，并计算总价格
        let amount = 0;
        let orderGoods = []; //待新建的订单商品列表
        for (let i = 0; i < goodsList.length; i++) {
            //判断每个商品库存数量是否满足
            let item = goodsList[i];
            let sql = `select * from goods where id = ${item.id} AND num >= ${item.count} AND status = 1`;
            let result = await query(sql);

            if (result.length == 0) throw `部分商品库存不足`;

            //继续处理该商品
            let goods = result[0];
            amount += goods.price * item.count;
            orderGoods.push({
                goods_id: item.id,
                count: item.count,
                price: goods.price,
            });

            //修改商品的库存数量
            sql = `update goods set num = num - ${item.count} where id=${item.id}`;
            await query(sql);
        }

        // 创建订单
        let order = {};
        order.user_id = user.id;
        order.address_name = address.name;
        order.address_tel = address.tel;
        order.address_detail = `${address.city}-${address.county}-${address.detail}`;
        order.note = note;
        order.amount = amount;
        sql = "INSERT INTO user_order SET ?";
        result = await query(sql, [order]);
        let order_id = result.insertId;  //获取新订单的编号
        //插入订单项数据
        for (let i = 0; i < orderGoods.length; i++) {
            let goods = orderGoods[i];
            goods.order_id = order_id; //订单商品记录添加订单编号值
            sql = "INSERT INTO user_order_goods SET ?";
            await query(sql, [goods]);
        }
        res.send({code: 1, msg: `创建订单成功`});

    } catch (error) {
        res.send({code: -1, msg: `创建订单失败, error: ${error}`}); //throw err;
    }
});

//===================================================
// 1.6.2 查询订单列表
// 参数名	参数说明	备注
// 无参数
router.get("/list", async (req, res) => {
    //是否已登录
    const token = req.headers.authorization // 取到请求头中Token
    let result = Token.verify(token);
    let user = result.data;

    try {
        //获取当前用户的订单
        let sql = `select * from v_user_order where user_id = ${user.id} `;
        let orders = await query(sql);
        // 获取每个订单的商品列表
        for (let i = 0; i < orders.length; i++) {
            let order = orders[i];
            let sql = `select  * from v_order_goods where order_id = ${order.id}`;
            let goodsList = await query(sql);
            order.goods = goodsList; //添加该订单的商品
        }

        res.send(response.success(orders, `订单查询成功`));
    } catch (error) {
        res.send(response.fail(`订单查询失败, error: ${error}`)); //throw err;
    }
});

router.get("/delivery", async (req, res) => {
    //是否已登录
    const token = req.headers.authorization // 取到请求头中Token
    let result = Token.verify(token);
    let user = result.data;

    try {
        //获取当前用户的订单
        let sql = `select * from v_order_goods where seller_id = ${user.id} `;
        let orders = await query(sql);
        res.send(response.success(orders, `订单查询成功`));
    } catch (error) {
        res.send(response.fail(`订单查询失败, error: ${error}`)); //throw err;
    }
});

//===================================================
// 1.6.3 查询订单详情 order/detail
// 参数名	参数说明	备注
// id	订单id
router.get("/detail", async (req, res) => {
    //是否已登录
    const token = req.headers.authorization // 取到请求头中Token
    let result = Token.verify(token);
    if (result.code != 1) {
        res.send({
            code: 401,
            msg: "Token错误，请登录验证!",
            data: {}
        });
        return;
    }
    let user = result.data;


    try {
        //请求参数
        let id = parseInt(req.query.id) || 0;
        if (!id) throw "查询的订单编号不能为空";

        //获取当前用户的订单
        let sql = `select * from user_order where id = ${id}`;
        let result = await query(sql);
        if (result.length != 1) throw "当前用户没有订单,或订单号重复了！";

        //当前用户有订单（只有1个)，则继续处理
        let order = result[0];
        // 获取订单的商品列表

        sql = `select * from v_order_goods where order_id = ${order.id}`;
        let goodsList = await query(sql);
        order.goods = goodsList; //添加该订单的商品

        let data = order;
        res.send({code: 1, msg: `订单查询成功`, data});
    } catch (error) {
        res.send({code: -1, msg: `订单查询失败, error: ${error}`}); //throw err;
    }
});

//===================================================
// 1.6.4 取消订单  order/cancel
// 参数名	参数说明	备注
// id	订单id
router.post("/cancel", async (req, res) => {
    //是否已登录
    const token = req.headers.authorization // 取到请求头中Token
    let result = Token.verify(token);
    if (result.code != 1) {
        res.send({
            code: 401,
            msg: "Token错误，请登录验证!",
            data: {}
        });
        return;
    }
    let user = result.data;

    try {
        //请求参数
        let id = parseInt(req.body.id) || 0; //POST从body中取参数
        if (!id) throw "取消的订单编号不能为空";

        //获取当前用户的订单  (包括已取消的)
        let sql = `select * from user_order where user_id = ${user.id} AND id = ${id}`;
        let result = await query(sql);
        if (result.length != 1)
            throw "当前用户没有订单或有重复的订单号记录！";

        //当前用户有一条订单，则继续处理
        let order = result[0];
        //获取该订单的商品列表

        sql = `select  * from v_order_goods where order_id = ${order.id}`;
        let goodsList = await query(sql);

        //订单商品数量要回加到对应商业的库存数
        for (let i = 0; i < goodsList.length; i++) {
            let item = goodsList[i];
            sql = `update goods set num = num + ${item.count} where id=${item.goods_id}`;
            await query(sql);
        }

        //设置订单的取消标志值
        sql = `update user_order set is_cancel = 1 where id=${order.id}`;
        await query(sql);
        res.send({code: 1, msg: `订单取消成功`});
    } catch (error) {
        res.send({code: -1, msg: `订单取消失败, error: ${error}`}); //throw err;
    }
});

router.post("/clear", async (req, res) => {
    let token = req.headers.authorization;
    let data = Token.verify(token);
    let userId = data.data.id
    let body = req.body;

    let sql = `delete from user_order where user_id=${userId}`
    await query(sql, body).then(result => {
        res.send(response.success(result))
    }).catch(ex => {
        res.send(response.serverEx(ex))
    })
})

router.post("/pay", async (req, res) => {
    let token = req.headers.authorization;
    let data = Token.verify(token);
    let userId = data.data.id
    let body = req.body;
    let amount = body.amount;
    let orderId = body.id;
    let goodsList = body.goods;
    let seller_id = ""

    try {
        let queryMoney = `select money from user where id=${userId} limit 1`
        let result = await query(queryMoney);
        let money = result[0].money;
        if (money < amount) {
            return response.sendError(res, "余额不足")
        }

        let changeMoney = `update user set money=money-${amount} where id=${userId}`
        let r = await query(changeMoney);

        // changeMoney = `update user set money=money+${amount} where id=${seller_id}`
        //  r = await query(changeMoney);
        // console.log(r)

        let updateOrder = `update user_order set status=1, is_cancel=0 where id=${orderId}`
        r = await query(updateOrder);
        console.log(r)

        for (let i in goodsList) {
            let goods = goodsList[i]
            let updateGoods = `update goods set num=num-${goods.count},status=if(num>0,status,2) where id=${goods.goods_id}`
            let r = await query(updateGoods);
            console.log(r)
            let deleteCart = `delete from user_cart where user_id=${userId} and goods_id=${goods.goods_id}`;
            result = await query(deleteCart);

            r = await query(updateGoods);
            console.log(r)
        }
        res.send(response.ok("支付成功"))
    } catch (ex) {
        res.send(response.serverEx(ex))
    }

})

router.put("/delivery", async (req, res) => {
    let token = req.headers.authorization;
    let data = Token.verify(token);
    let userId = data.data.id
    let body = req.body;
    let order_goods_id = body.id

    try {
        let sql = `update user_order_goods set is_delivery=1 where id=${order_goods_id}`
        let result = await query(sql);
        let callProcedure = `call get_delivery(${order_goods_id})`
        await query(callProcedure)
        res.send(response.success(result))
    } catch (ex) {
        res.send(response.serverEx(ex))
    }


})

router.put("/receipt", async (req, res) => {
    let token = req.headers.authorization;
    let data = Token.verify(token);
    let userId = data.data.id
    let orderId = req.body.id;

    let sql = `update user_order set status=3 where id=${orderId}`
    await query(sql, []).then(result => {
        res.send(response.success(result))
    }).catch(ex => {
        res.send(response.serverEx(ex))
    })
})

router.get("/undelivery", async (req, res) => {
    let token = req.headers.authorization;
    let data = Token.verify(token);
    let userId = data.data.id
    let body = req.body;

    let sql = `select * from v_order_goods where seller_id=${userId} and is_delivery=0`
    await query(sql).then(result => {
        res.send(response.success(result))
    }).catch(ex => {
        res.send(response.serverEx(ex))
    })
})

//===============================================
//导出路由器
module.exports = router;
